package com.cnebula.openapi.auth.authtoken.impl;

import com.cnebula.openapi.auth.authtoken.PrivilegeClientKeyService;

import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PrivilegeClientKeyServiceImpl implements PrivilegeClientKeyService {

	private String okapiUrl = null;
	private Vertx vertx;
	private String requestToken;
	private String tenant;
	private int timeout = 10;
	private final Logger logger = LoggerFactory.getLogger(PrivilegeClientKeyServiceImpl.class);

	public PrivilegeClientKeyServiceImpl(Vertx vertx) {
		this.vertx = vertx;
	}

	@Override
	public void setOkapiUrl(String url) {
		okapiUrl = url;
		if (!okapiUrl.endsWith("/")) {
			okapiUrl = okapiUrl + "/";
		}
	}

	@Override
	public void setRequestToken(String token) {
		requestToken = token;
	}

	@Override
	public void setTenant(String tenant) {
		this.tenant = tenant;
	}

	@Override
	public void setRequestTimeout(int seconds) {
		this.timeout = seconds;
	}

	@Override
	public Future<Void> checkKey(String clientKey, String clientIp) {
		Future<Void> future = Future.future();

		HttpClientOptions options = new HttpClientOptions();
		options.setConnectTimeout(timeout * 1000);
		HttpClient client = vertx.createHttpClient(options);
		String okapiUrlCandidate = "http://localhost:9130/";
		if (okapiUrl != null) {
			okapiUrlCandidate = okapiUrl;
		}
		final String okapiUrlFinal = okapiUrlCandidate;
		String checkClientRequestUrl = okapiUrlFinal + "client/check?client_id="+clientKey+"&ip="+clientIp;
		logger.debug("Requesting check client  from URL at " + checkClientRequestUrl);

		HttpClientRequest req = client.getAbs(checkClientRequestUrl);

		req.putHeader("X-Okapi-Token", requestToken)
		   .putHeader("X-Okapi-Tenant", tenant)
		   .putHeader("Content-Type", "application/json")
		   .putHeader("Accept", "application/json");

		req.handler(h ->{
			h.bodyHandler(res ->{
				if(h.statusCode() != 200){
					future.fail(res.toString());
				}else{
					future.complete();
				}
			});
		});
		req.exceptionHandler(e -> {future.fail(e);});
		req.end();
		

		return future;
	}

}
